package com.example.myapplication;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ParticleView extends View {
    private Bitmap bitmap;
    private List<Particle> particles = new ArrayList<>();
    private Paint paint = new Paint();
    private ValueAnimator animator;
    private int viewWidth, viewHeight;
    private Random random = new Random();

    public ParticleView(Context context) {
        super(context);
        init();
    }

    public ParticleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
    }

    public void setImage(Bitmap bitmap) {
        this.bitmap = bitmap;
        createParticles();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;
        viewHeight = h;
        createParticles();
    }

    private void createParticles() {
        particles.clear();
        Log.d("TAG", "createParticles: "+viewHeight+"======="+viewWidth);
        if (bitmap == null || viewWidth == 0 || viewHeight == 0) return;

        int step = 4; // 控制粒子密度，值越大粒子越少
        int bmWidth = bitmap.getWidth();
        int bmHeight = bitmap.getHeight();

        // 计算图片在View中的起始位置（居中）
        int startX = (viewWidth - bmWidth) / 2;
        int startY = (viewHeight - bmHeight) / 2;

        for (int x = 0; x < bmWidth; x += step) {
            for (int y = 0; y < bmHeight; y += step) {
                int color = bitmap.getPixel(x, y);
                // 转换为View中的坐标
                float particleX = startX + x;
                float particleY = startY + y;
                particles.add(new Particle(particleX, particleY, color));
            }
        }
    }

    public void startAnimation() {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        isStartAnimation  = true;
        animator = ValueAnimator.ofFloat(0, 1);
        animator.setDuration(1500); // 动画时长
        animator.addUpdateListener(animation -> {
            float progress = (float) animation.getAnimatedValue();
            updateParticles(progress);
            invalidate();
        });
        animator.start();
    }

    private void updateParticles(float progress) {
        Log.d("TAG", "updateParticles: "+progress);
        for (Particle particle : particles) {
            particle.update(progress);
        }
    }
    boolean isStartAnimation= false;
    public void reset(){
        Log.d("TAG", "reset: ");
        isStartAnimation =false;
//        paint.setAlpha(1);
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        invalidate();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d("TAG", "onDraw: "+ bitmap+"======"+viewWidth+"====="+viewHeight);
        if (bitmap == null || viewWidth == 0 || viewHeight == 0) return;
        if(!isStartAnimation) {
            Log.d("TAG", "onDraw: 原始");
            int bmWidth = bitmap.getWidth();
            int bmHeight = bitmap.getHeight();

            int startX = (viewWidth - bmWidth) / 2;
            int startY = (viewHeight - bmHeight) / 2;
            paint.reset();
            canvas.drawBitmap(bitmap, startX,startY, paint);
        } else {
            Log.d("Tag", "onDraw: 开启动画");
            for (Particle particle : particles) {
                paint.setColor(particle.getColor());
                paint.setAlpha(particle.getAlpha());
                canvas.drawRect(particle.x, particle.y, particle.x + 2 * particle.radius, particle.y + 2 * particle.radius, paint);
            }
        }

    }

    private class Particle {
        float startX, startY;
        float x, y;
        int color;
        float velocityX, velocityY;

        public int getAlpha() {
            return alpha;
        }

        public void setAlpha(int alpha) {
            this.alpha = alpha;
        }

        int alpha;
        float radius =2f; // 粒子半径

        Particle(float x, float y, int color) {
            this.startX = x;
            this.startY = y;
            this.x = x;
            this.y = y;
            this.color = color;
            this.alpha = Color.alpha(color);

            // 随机生成速度和方向
            double angle = random.nextDouble() * 2 * Math.PI;
            float speed = random.nextFloat() * 10 + 5; // 速度范围5-15
            velocityX = (float) (Math.cos(angle) * speed);
            velocityY = (float) (Math.sin(angle) * speed);
        }

        void update(float progress) {
            // 更新位置：初始位置 + 速度 * 进度
            x = startX + velocityX * progress * 50; // 50为距离系数
            y = startY + velocityY * progress * 50;
            alpha = (int) (Color.alpha(color) * (1 - progress));
        }

        int getColor() {
            return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
        }
    }
}